#!/usr/bin/env python3

# Copyright (c) 2020-2025 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import re
import pathlib
from .._errors import InvalidAuxillaryTargetError
from ._target import Target


class AuxillaryTarget(Target):

    # we don't adhere to systemd's native classification scheme, which is confusing
    #
    # auxillary target must be user-aware, user should be able to enable/disable, start/stop an auxillary target
    # auxillary targets should not depends on or conflict with each other
    # only some of the systemd build-in targets are our "auxillary target", for custom auxillary target, there must be flags in its config file
    #

    @classmethod
    def _create(cls, parent, dir_path, **kwargs):
        unitName = kwargs["name"] + ".target"
        fullfn = os.path.join(dir_path, unitName)
        pathlib.Path(fullfn).write_text(cls._generateAuxillaryTargetFileContent(kwargs["name"], kwargs["description"]))
        return cls(parent, unit_name=unitName)

    @classmethod
    def _exists(cls, parent, dir_path, **kwargs):
        unitName = kwargs["name"] + ".target"
        fullfn = os.path.join(dir_path, unitName)
        if not os.path.exists(fullfn):
            return None
        if pathlib.Path(fullfn).read_text() != cls._generateAuxillaryTargetFileContent(kwargs["name"], kwargs["description"]):
            return None
        return cls(parent, unit_name=unitName)

    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)

        if self._unitName not in _buildInAuxTargets:
            if re.search("^# Auxillary target$", self.unit_file_content, re.M) is None:
                raise InvalidAuxillaryTargetError(self.unit_file_path)

    def is_enabled(self):
        pass

    def enable(self):
        pass

    def disable(self):
        pass

    def remove_and_dispose(self):
        assert not self.is_enabled()
        super().remove_and_dispose()

    @staticmethod
    def _generateAuxillaryTargetFileContent(name, description):
        buf = ""
        buf += "# Auxillary target\n"
        buf += "[Unit]\n"
        buf += "Description=%s\n" % (description)
        return buf


_buildInAuxTargets = [
]
